#include "http_download.h"
#include <stdio.h>
#include <stdbool.h>
#include <time.h>

/**
 * @brief 自定义日志输出函数
 * @param log_msg 日志信息
 */
void custom_log_callback(const char* log_msg) {
    // 获取当前时间
    time_t now = time(NULL);
    struct tm* tm_info = localtime(&now);
    char time_str[20];
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", tm_info);

    printf("[%s] %s\n", time_str, log_msg);
}

/**
 * @brief 下载进度回调函数
 * @param total_bytes 总字节数
 * @param downloaded_bytes 已下载字节数
 * @return 是否继续下载，true继续，false取消
 */
bool progress_callback(uint64_t total_bytes, uint64_t downloaded_bytes) {
    // 每下载10%的进度打印一次
    static uint32_t last_percent = 0;
    if (total_bytes > 0) {
        uint32_t percent = (downloaded_bytes * 100) / total_bytes;
        if (percent >= last_percent + 10 || percent == 100) {
            printf("Progress: %d%% (%llu/%llu bytes)\n", percent, downloaded_bytes, total_bytes);
            last_percent = percent;
        }
    }

    // 这里可以添加条件来取消下载
    // 例如：如果下载时间超过某个值，或者用户按下某个键

    return true; // 继续下载
}

int main(int argc, char* argv[]) {
    // 初始化HTTP下载器
    if (http_download_init() != 0) {
        printf("Failed to initialize HTTP downloader: %s\n", http_download_get_error());
        return -1;
    }

    printf("HTTP downloader initialized successfully.\n");

    // 设置下载选项
    http_download_options_t options = {
        .url = "http://o-bos.com:9004/files/20250818/100267.img",  // 100MB的测试文件，从httpbin.org获取
        .save_path = ".\\downloads\\test_file.img", // 保存到当前目录下的downloads文件夹
        .timeout_ms = 30000,  // 30秒超时
        .buffer_size = 16384, // 16KB缓冲区
        .resume_download = true,  // 支持断点续传
        .log_callback = custom_log_callback  // 自定义日志回调
    };

    // 执行下载
    printf("Starting download from %s\n", options.url);
    int result = http_download_file(&options, progress_callback);

    if (result == 0) {
        printf("Download completed successfully!\n");
    } else {
        printf("Download failed: %s\n", http_download_get_error());
    }

    // 清理资源
    http_download_cleanup();

    return result;
}